﻿#version 400
uniform mat4 ModelViewMatrix;
uniform mat4 ProjectionMatrix;
uniform mat4 SkinningMatrix[16];
uniform mat3 NormalSkinningMatrix[16];

in vec3 v_Position;
in vec3 v_Normal;
in ivec4 v_BoneIndex;
in vec4 v_BoneWeight;

out vec3 f_Position;
out vec3 f_Normal;

void main(void)
{
    bool transformed = false;
    vec3 pos = vec3(0,0,0);
	vec3 norm = vec3(0,0,0);

    for (int i = 0; i < 4; i++) {
	    if (v_BoneIndex[i] >= 0) {
			mat4  m1 = SkinningMatrix[i];
            mat3  m2 = NormalSkinningMatrix[v_BoneIndex[i]];
		    float w  = v_BoneWeight[i];
		    pos += (w * m1 * vec4(v_Position, 1.0)).xyz;
			norm += w * m2 * v_Normal;
            transformed = true;
        }
	}

	if (transformed) {
        f_Position = pos;
        f_Normal   = norm;
	}else{
	    f_Position = v_Position;
        f_Normal   = v_Normal;
    }

    gl_Position = ProjectionMatrix * ModelViewMatrix * vec4(v_Position, 1);
}